package com.kuizii.server.net;


import com.kuizii.server.discovery.RegisterProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;


/**
 * @author renxiaodong
 */
public class NettyIOManager implements IOManager {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;
    ApplicationContext applicationContext;
    RegisterProperties properties;

    public NettyIOManager(RegisterProperties properties, ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        this.properties = properties;
    }

    @Override
    public void init(RegisterProperties properties) {

        try {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            //设置TCP缓冲区
            //设置发送数据缓冲大小
            //设置接受数据缓冲大小
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.SO_SNDBUF, 32 * 1024)
                    .option(ChannelOption.SO_RCVBUF, 32 * 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            logger.debug("建立连接.." + pipeline.channel().remoteAddress());

//                    pipeline.addLast(new IdleStateHandler(15,15,15,TimeUnit.SECONDS));
//                    pipeline.addLast(new HealthBeatServerHandler());
//                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
//                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(new ObjectDecoder(ClassResolvers.weakCachingResolver(this.getClass().getClassLoader())));
                            pipeline.addLast(new DefaultMessageReceiverHandler(applicationContext));
//                            pipeline.addLast(new DefaultMessageEncoder());
//                            pipeline.addLast(new DefaultMessageDecoder());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.bind(9527).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }


//    @Override
//    public void registerService(LiteServiceRegistration instance) {
//        registerEventListener.triggerEvent(EventType.REGISTER, instance);
//    }
//
//    @Override
//    public void deregisterService(String serviceName, LiteServiceRegistration instance) {
//        registerEventListener.triggerEvent(EventType.UNREGISTER, instance);
//    }
//
//    @Override
//    public void healthCheckService(String serviceName, LiteServiceRegistration instance) {
//        workerGroup.scheduleAtFixedRate(() -> {
//            bootstrap.childHandler(new DefaultMessageEncoder());
//            registerEventListener.triggerEvent(EventType.HEALTH_CHECK, instance);
//        }, 0, 15, TimeUnit.SECONDS);
//    }
}
